import React, {useEffect} from 'react'
import {useDispatch, useSelector} from 'react-redux'
import { View, 
  Text, SafeAreaView, StyleSheet, Image, ScrollView, TouchableWithoutFeedback, StatusBar } from 'react-native'
import { SwipeAction, Toast } from '@ant-design/react-native';
import moment from 'moment'
import { Header, SearchBar } from '../../components'
import { GET, pxToPt, timeFomet } from '../../utils'
import {themes} from '../../theme'
import { MESSAGE_SWIPEACTION } from '../../config/dev';
import { GetUserFriendRequest, USERINFOURL } from '../../service';
import { 
  AutoLogin, 
  RecoverUserInfoOnInit, 
  InitUserFriendRequest,
  GetUserFriendList,
} from '../../store/reducer/user';
import { useNavigation } from '@react-navigation/native';
import Socket from '../../socket'
import { RecoverMessageOnInit } from '../../store/reducer/message';



export default function index() {
  const dispatch = useDispatch()
  const navigation = useNavigation()
  const recent = useSelector(state => state.message.recent);
  const messageMap = useSelector(state => state.message.messageMap);
  const totalMessage = useSelector(state => state.message.totalMessage);
  const friendMap = useSelector(state => state.user.friendMap);

 
  const recentMessage = [{
    friendId: 1,
    last_message: '吃了吗？在干嘛呢, 我是admin',
    unreadNumber:3
  },
  {
    friendId: 8,
    last_message: '去踏春去吧,我是admin2',
    unreadNumber:1
  },
]
  useEffect(async () => {
    init()
    return () => {
    }
  }, [])

  const init = async () => {
    const res = await dispatch(AutoLogin())
    if (!res.status) {
        Toast.info(res.errmsg)
      navigation.reset({
        index: 0,
        routes: [
          {
            name: 'Login'
          }
        ]
      })
      return
    }

    await dispatch(RecoverUserInfoOnInit())
    await dispatch(RecoverMessageOnInit())
    await Socket.setUp()
    await refresh()
  }
  const refresh = async () => {
    await dispatch(InitUserFriendRequest())
    await dispatch(GetUserFriendList())
  }
  const chatToUser = (fid) => {
    navigation.navigate('Chating', {fid})
  }
  return (
    <SafeAreaView style={{backgroundColor: themes['light'].bg, flex: 1}}>
      <View style={styles.container}>
        <StatusBar translucent={true} backgroundColor="transparent" />
        <Header title="消息" />
        <ScrollView>
          <View>
            {
              recent.map(item=>{
                const {fid, last_message, unreadNumber } = item
                const friendInfo = friendMap[fid]
                return (
                  <SwipeAction
                    autoClose
                    style={{ backgroundColor: 'transparent' }}
                    right={MESSAGE_SWIPEACTION.right}
                    left={MESSAGE_SWIPEACTION.left}
                    onOpen={() => console.log('open')}
                    onClose={() => console.log('close')}
                  >
                    <TouchableWithoutFeedback onPress={()=>{chatToUser(fid)}}>
                      <View style={styles.message}>
                        <Image style={styles.avatar} onPress={()=>navigation.navigate('PersonalHomePage', {fid})} source={require('../../../assets/bg/woman.jpeg')} /> 
                        <View style={styles.messageMain}>
                          <View style={styles.top}>
                            <Text style={{fontSize: pxToPt(20), color:themes['light'].color}}>{friendInfo?.fname}</Text>
                            <Text style={{fontSize: pxToPt(12), color: themes['light'].secondColor}}>{timeFomet(messageMap[last_message]?.create_time)}</Text>
                          </View>
                          <View style={styles.bottom}>
                            <Text numberOfLines={1} style={{fontSize: pxToPt(13), color: themes['light'].secondColor, flex: 1}}>{messageMap[last_message]?.content}</Text>
                            {unreadNumber>0&&<View style={styles.unreadNumber}><Text style={{textAlign: 'center', lineHeight: pxToPt(20), color: '#fff'}}>{unreadNumber}</Text></View>}
                          </View>
                        </View>
                      </View>
                    </TouchableWithoutFeedback>
                  </SwipeAction>
                )
              })
            }
          </View>
        </ScrollView>
      </View>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    paddingLeft: pxToPt(20),
    paddingRight: pxToPt(20),
    flex: 1
  },
  message: {
    height: pxToPt(70),
    alignItems: 'center',
    flexDirection: 'row',
  },
  avatar: {
    alignSelf: 'flex-start',
    width: pxToPt(40),
    height: pxToPt(40),
    borderRadius: pxToPt(50)
  },
  messageMain: {
    flex: 1,
    height: '100%',
    marginLeft: pxToPt(20)
  },
  top: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: pxToPt(10)
  },
  bottom: {
    flexDirection: 'row',
  },
  unreadNumber: {
    width: pxToPt(20),
    height: pxToPt(20),
    backgroundColor: 'pink',
    borderRadius: pxToPt(6)
    
  },
  name: {
    color: 'white',
    fontSize: pxToPt(20)
  },
  time:{
    fontSize: pxToPt(12),
    color: 'gray'
  },
  chatInfo: {
    color: 'gray',
    fontSize: pxToPt(13),
  }

})